/*
 * @Author: xusun000「xusun000@foxmail.com」 
 * @Date: 2022-08-03 10:38:39 
 * @Last Modified by:   xusun000 
 * @Last Modified time: 2022-08-03 10:38:39 
 */
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_sensor_backend/assets/storage.dart';

String base_url = "http://124.223.62.14:8080";

class ServerConfig {
  String url = base_url + "";
}

bool isLog = true; //控制是否打印网络输出日志

class XHttp {
  netWorkRequest({
    String url = "",
    Map<String, dynamic>? header,
    Map? param, //参数
  }) async {
    var dio = Dio();
    dio.options.baseUrl = ServerConfig().url;
    dio.options.contentType = Headers.formUrlEncodedContentType;
    dio.options.responseType = ResponseType.plain;
    dio.options.connectTimeout = 10000;
    dio.options.receiveTimeout = 10000;
    dio.options.headers = header;
    if (isLog) print("地址:$url入参:$param");
    Response response = await dio
        .request(url, data: param, options: Options(method: "POST"))
        .catchError(
      (err) {
        if (isLog) print("${err}");
      },
    );
    // ignore: unnecessary_null_comparison
    if (response != null) {
      Map<String, dynamic> data = jsonDecode(response.toString());
      if (isLog) print("地址:$url入参:$param回参:$data");
      return data;
    } else {
      print(response.toString());
      return {};
    }
  }

  post({
    Map? param,
    required String url,
  }) async {
    String token = await getStorage(key: "token", initData: "");
    print("Token为：" + token);
    param = param ?? {};
    return await netWorkRequest(
      url: url,
      param: param,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": token,
      },
    );
  }
}
